<template>
  <a-row :gutter="[16, 16]" class="search">
    <a-col :span="4">
      <a-input v-model:value="SearchInfo.user" placeholder="用户名"/>
    </a-col>
    <a-col :span="4">
      <a-input v-model:value="SearchInfo.role" placeholder="角色"/>
    </a-col>
    <a-col :span="4" class="btn">
      <a-button :icon="h(SearchOutlined)" type="primary" @click="searchUser"
      >搜索
      </a-button
      >
      <a-button :icon="h(RedoOutlined)" @click="restTable">重置</a-button>
    </a-col>
  </a-row>
  <Table ref="TableRef" v-model:formState="formState" :columns="columns" :data="TableData"
         :refresh="get_TableData" :resetForm="resetForm" :tableHeaderButton="tableHeaderButton">
    <a-form
        ref="formRef"
        :label-col="labelCol"
        :model="formState"
        :rules="rules"
        :wrapper-col="wrapperCol"
    >
      <a-form-item ref="user" label="用户" name="user_id">
        <a-select v-model:value="formState.user_id" placeholder="请选着一个用户">
          <a-select-option
              v-for="(item, index) in userList"
              :key="index"
              :value="item.id"
          >{{ item.username }}
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item ref="role" label="角色" name="role_id">
        <a-select v-model:value="formState.role_id" placeholder="请选择一个角色">
          <a-select-option
              v-for="(item, index) in roleList"
              :key="index"
              :value="item.id"
          >{{ item.name }}
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 24}">
        <div style="width: 100%;display: flex;align-items: center;justify-content: end;">
          <a-button style="margin: 0 20px" @click="close">取消</a-button>
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </div>
      </a-form-item>
    </a-form>
  </Table>
</template>

<script setup>
import {message} from "ant-design-vue";
import {
  addUserRole,
  delUserRole,
  get_allRole,
  get_allUser,
  get_AuthAllUser,
  search_AuthAllUser,
  updateUserRole
} from "@/api/auth.js";
import {RedoOutlined, SearchOutlined} from "@ant-design/icons-vue";
import Table from "@/components/Table/index.vue";
import {h, reactive, ref, toRaw} from "vue";

const TableRef = ref('')
let TableData = ref([]);
const SearchInfo = reactive({
  user: "",
  role: "",
});
// 表格配置项
const columns = [
  {
    title: "用户名",
    key: "name",
    dataIndex: "name",
  },
  {
    title: "角色",
    key: "role",
    dataIndex: "role",
  },
  {
    title: "电话",
    key: "phone",
    dataIndex: "phone",
    width: 150,
  },
  {
    title: "邮箱",
    key: "email",
    dataIndex: "email",
    width: 150,
  },
  {
    title: "创建时间",
    key: "createTime",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    key: "action",
    width: 300,
    btn: [{
      type: 'edit',
      key: ['user_id']
    },
      {
        type: 'del',
        callback: delUserRole,
        key: ['user_id', 'role_id']
      }],
  },
];
const tableHeaderButton = ['add', 'export', 'delete']
// 搜索
const searchUser = async () => {
  if (SearchInfo.user === "" && SearchInfo.role === "") {
    message.error("查询不能为空");
    return;
  }
  let res = await search_AuthAllUser(toRaw(SearchInfo));
  if (!res) return;
  TableData.value = handelData(res.data);
};
// 重置
const restTable = () => {
  SearchInfo.user = "";
  SearchInfo.role = "";
  get_TableData();
};
// 查询table数据
const get_TableData = async () => {
  let res = await get_AuthAllUser();
  if (!res) return;
  TableData.value = handelData(res.data);
};
// 处理表格数据
const handelData = (data) => {
  return data.map(({id, user, role}) => ({
    id: id,
    name: user.username,
    user_id: user.id,
    role: role.name,
    role_id: role.id,
    createTime: role.create_time,
    phone: user.phone,
    email: user.email,
    code: role.code,
  }));
};

// 关闭Model
const close = () => {
  TableRef.value.closeModel()
}

// 表单
const formRef = ref();
let userList = ref([]);
let roleList = ref([]);
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const formState = ref({
  user_id: "",
  role_id: "",
});
const rules = {
  user_id: [
    {
      required: true,
      message: "请选择一个用户",
      trigger: "change",
    },
  ],
  role_id: [
    {
      required: true,
      message: "请选择一个角色",
      trigger: "change",
    },
  ],
};
// 提交
const onSubmit = () => {
  const type = TableRef.value.statusType
  const data = TableRef.value.editId
  formRef.value
      .validate()
      .then(async () => {
        let res = await requestData(type, data)
        if (!res) return;
        if (res.status === 400) message.error(res.data)
        if (res.status === 200) message.success(res.data)
        // 重新请求数据
        await get_TableData()
        close()
        resetForm()
      })
      .catch((error) => {
        console.log("error", error);
      });
};

const requestData = async (type, data) => {
  if (type === 'add') {
    return await addUserRole({...formState.value})
  }
  if (type === 'edit') {
    return await updateUserRole({user_id: data['user_id'], role_id: formState.value['role_id']})
  } else {
    console.log('错误方式')
    return {data: '错误方式'}
  }
}
// 重置
const resetForm = () => {
  if (formRef.value) formRef.value.resetFields();
  formState.value = {
    user_id: "",
    role_id: "",
  }
};

// 获取所有的权限
const GetRoleList = async () => {
  let res = await get_allRole();
  if (!res) return;
  roleList.value = res.data;
};
// 获取所有的用户
const GetUserList = async () => {
  let res = await get_allUser();
  if (!res) return;
  userList.value = res.data;
};

get_TableData();
GetRoleList();
GetUserList();
</script>

<style lang="scss" scoped>
.search {
  .btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    gap: 15px;
  }
}
</style>